package com.gidgabs.modules.api.service.discovery;

import com.gidgabs.common.utils.Assist;
import com.gidgabs.common.utils.DeleteType;
import com.gidgabs.common.utils.LangUtil;
import com.gidgabs.common.utils.ReturnJson;
import com.gidgabs.dto.TbUserDto;
import com.gidgabs.modules.dao.TbUserDao;
import com.gidgabs.modules.dao.TbUserFollowDao;
import com.gidgabs.modules.dao.TbUserJournalDao;
import com.gidgabs.modules.entity.TbUser;
import com.gidgabs.modules.entity.TbUserFollowEntity;
import com.gidgabs.modules.entity.TbUserJournalEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 发现模块服务类
 * Created by tby on 2018/7/3.
 */
@Service
public class DiscoveryUserService {
    @Autowired
    private TbUserDao tbUserDao;
    @Autowired
    private TbUserFollowDao tbUserFollowDao;
    @Autowired
    private TbUserJournalDao tbUserJournalDao;

    /***
     * (按照粉丝数量排序)
     * @param pageSize
     * @param pageNo
     * @param chooseType
     * @param chooseType
     * @return
     */
    @Transactional(readOnly = true)
    public ReturnJson<TbUserDto> queryList(Integer pageSize, Integer pageNo, Integer chooseType) {

        Assist assist = new Assist();
        Assist.WhereOrder fans_count = Assist.order("fans_count", false);
        assist.andEq("delete_type", DeleteType.NOT_DELETE.getKey())
                .andEq("choose_type", chooseType);
        assist.setOrder(fans_count);
        assist.setRowSize(pageSize);
        assist.setStartRow(LangUtil.firstLimit(pageSize, pageNo));
        List<TbUser> tbUsers = tbUserDao.selectTbUser(assist);
        long count = tbUserDao.getTbUserRowCount(assist);
        List<TbUserDto> tbUserDtos = new ArrayList<>();
        for (TbUser tbUser : tbUsers) {
            TbUserDto tbUserDto = tbUser.toDto();
            tbUserDtos.add(tbUserDto);

            TbUserJournalEntity lastJournal = findLastJournal(tbUser.getUserId());
            if (lastJournal != null) {
                tbUserDto.setLastLinkId(lastJournal.getId());
                tbUserDto.setLastLinkImg(lastJournal.getPictureUrl());
            }
            //获取相关的日志

        }
        return ReturnJson.success("查询成功", tbUserDtos, count, pageSize, pageNo);
    }


    /**
     * 查询用户最近一条发布的日志
     *
     * @param userId
     * @return
     */

    private TbUserJournalEntity findLastJournal(Integer userId) {

        Assist assist = new Assist();
        assist.andEq("user_id", userId).andEq("delete_type", DeleteType.NOT_DELETE.getKey());

        Assist.WhereOrder create_timeOrder = Assist.order("create_time", false);
        assist.setOrder(create_timeOrder);
        assist.setRowSize(1);
        assist.setStartRow(0);
        List<TbUserJournalEntity> tbUserJournalEntities = tbUserJournalDao.selectTbUserJournal(assist);
        if (tbUserJournalEntities.size() == 0) {
            return null;
        } else {
            return tbUserJournalEntities.get(0);
        }
    }

    /**
     * 关注或者取消关注某个用户
     *
     * @param userId 被关注的用户
     * @param tbUser 当前登录人
     * @return
     */
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public ReturnJson follow(Integer userId, TbUser tbUser) {
        Assist assist = new Assist();
        assist.andEq("user_id_master", tbUser.getUserId()).andEq("user_id_slave", userId);
        List<TbUserFollowEntity> tbUserFollowEntities = tbUserFollowDao.selectTbUserFollowEntity(assist);
        TbUser forUpdateUser = tbUserDao.getForUpdate(userId);
        //取消关注
        if (tbUserFollowEntities.size() > 0) {
            tbUserFollowDao.deleteTbUserFollowByAssist(assist);
            forUpdateUser.setFansCount(forUpdateUser.getFansCount() - 1);

        } else {//关注
            TbUserFollowEntity tbUserFollowEntity = new TbUserFollowEntity(tbUser.getUserId(), userId);
            tbUserFollowDao.insertNotNullTbUserFollowEntity(tbUserFollowEntity);
            forUpdateUser.setFansCount(forUpdateUser.getFansCount() + 1);
        }
        tbUserDao.updateTbUserById(forUpdateUser);
        return ReturnJson.success("操作成功");
    }

    /**
     * 按名称/编号 模糊搜索用户
     *
     * @param like
     * @param chooseType
     * @return
     */
    @Transactional(readOnly = true)
    public ReturnJson<TbUserDto> userSearch(String like, Integer chooseType) {

        Assist assist = new Assist(
                Assist.whereRequire("and (user_code like ", "%" + like + "%"),
                Assist.whereRequire("or user_name like ", "%" + like + "%", ")"));

        if (chooseType != null && chooseType != 0) {
            assist.andEq("choose_type", chooseType);
        }
        List<TbUserDto> tbUserDtos = tbUserDao.selectTbUser(assist).stream()
                .map(TbUser::toDto)
                .collect(Collectors.toList());

        return ReturnJson.success("查询成功", tbUserDtos);
    }
}
